package demo.reflect;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @author zhanghaixuan
 * @date 2020-03-05 10:53
 */
@Slf4j
public class ConstrctorCollector {

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class<?> clazz = Class.forName("demo.reflect.ReflectTarget");
        /**
         * 获取所有的公有构造方法
         */
        Constructor[] constructor = clazz.getConstructors();
        for (Constructor constructor1 : constructor) {
            log.info("clazz.getConstructors() 获取的方法  :   {}",constructor1);
        }

        Constructor<?>[] declaredConstructors = clazz.getDeclaredConstructors();
        for (Constructor constructor1 : declaredConstructors) {
            log.info("clazz.getDeclaredConstructors() 获取的方法  :   {}",constructor1);
        }

        log.info("获取公有的带两个参数的构造方法");
        Constructor<?> constructor1 = clazz.getConstructor(String.class, int.class);
        log.info("获取公有的带两个参数的构造方法,{}",constructor1);

        log.info("获取私有的构造方法");
        Constructor<?> declaredConstructor = clazz.getDeclaredConstructor(int.class);
        log.info("获取私有的构造方法,{}",declaredConstructor);


        log.info("调用私有构造方法创建实例");
        declaredConstructor.setAccessible(true);
        Object o = declaredConstructor.newInstance(1);
        log.info(o.toString());
    }
}
